﻿using Raffles.OA.Utility;
using Raffles.OA.Data;
using Raffles.OA.WebApp.App_Filter;
using SqlSugar;
using System.IO;
using System;
using System.Web.Mvc;
using System.Text;
using System.Net.Mail;
using System.Net.Mime;
using System.Web;

namespace Raffles.OA.WebApp
{
    /// <summary>
    /// 控制器基类
    /// </summary> 
    [Login]
    public class BaseController<TEntity> : Controller where TEntity : BaseEntity, new()
    { 
        public static SqlSugarScope _dbContext = ReportDB.Db;
        #region 视图
        
        public virtual ActionResult Index()
        {
            return View();
        } 

        #endregion

        #region 操作

        /// <summary>
        /// 表单赋值
        /// </summary>
        /// <param name="KeyValue">主键值</param>
        /// <returns></returns>
        public virtual ActionResult SetForm(int id)
        {
            TEntity entity = _dbContext.Queryable<TEntity>().InSingle(id); 
            return Content(DataResult<TEntity>.Success(entity).ToJson());
        }

        #endregion

        #region 文件导出

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>

        [HttpGet]
        public FileContentResult ExportFile(string filePath)
        {
            string absoluteFilePath = AppDomain.CurrentDomain.BaseDirectory + Path.DirectorySeparatorChar + filePath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
            try
            {
                DataResult<FileContentResult> obj = new DataResult<FileContentResult>();
                byte[] fileBytes = System.IO.File.ReadAllBytes(absoluteFilePath);
                string fileNamePrefix = DateTime.Now.ToString("yyyyMMddHHmmss");
                string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filePath);
                string title = string.Empty;
                if (fileNameWithoutExtension.Contains("_"))
                {
                    title = fileNameWithoutExtension.Split('_')[1].Trim();
                }
                string fileExtensionName = Path.GetExtension(filePath);
                obj.data = new FileContentResult(fileBytes, "application/octet-stream")
                {
                    FileDownloadName = string.Format("{0}_{1}{2}", fileNamePrefix, title, fileExtensionName)
                };
                return obj.data;

            }
            catch (Exception ex)
            {
                throw new Exception("下载失败:" + ex.Message);
            }
            finally
            {
                if (System.IO.File.Exists(absoluteFilePath))
                {
                    System.IO.File.Delete(absoluteFilePath);
                }
            }
        }

        #endregion 文件导出 

        #region 文件下载

        /// <summary>
        /// 下载附件
        /// </summary>
        /// <param name="attachAddress">附件路径</param>
        /// <returns></returns>
        public ActionResult DownloadFile(string attachAddress)
        {
            attachAddress= attachAddress.Replace("'", "");
            string appDirectory = AppDomain.CurrentDomain.BaseDirectory;
            string filePath = Path.Combine(appDirectory, attachAddress.TrimStart('\\'));
            Encoding encoding;
            string outputFileName = null;
            string fileName = Path.GetFileName(filePath);

            string browser = Request.UserAgent.ToUpper();
            if (browser.Contains("MS") == true && browser.Contains("IE") == true)
            {
                outputFileName = HttpUtility.UrlEncode(fileName);
                encoding = Encoding.Default;
            }
            else if (browser.Contains("FIREFOX") == true)
            {
                outputFileName = fileName;
                encoding = Encoding.GetEncoding("GB2312");
            }
            else
            {
                outputFileName = HttpUtility.UrlEncode(fileName); 
                encoding = Encoding.Default;
            }
            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            byte[] bytes = new byte[(int)fs.Length];
            fs.Read(bytes, 0, bytes.Length);
            fs.Close();
            Response.Charset = "UTF-8";
            Response.ContentType = "application/octet-stream";
            Response.ContentEncoding = encoding;
            Response.AddHeader("Content-Disposition", "attachment; filename=" + outputFileName);
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();
            return new EmptyResult();
        }

        #endregion

        #region 模板下载

        /// <summary>
        /// 下载导入模板
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <returns></returns>
        public ActionResult DownloadTemplateFile(string fileName)
        { 
            string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Template");
            Encoding encoding;
            string outputFileName = null;
            fileName = fileName.Replace("'", "");

            string browser = Request.UserAgent.ToUpper();
            if (browser.Contains("MS") == true && browser.Contains("IE") == true)
            {
                outputFileName = HttpUtility.UrlEncode(fileName);
                encoding = Encoding.Default;
            }
            else if (browser.Contains("FIREFOX") == true)
            {
                outputFileName = fileName;
                encoding = Encoding.GetEncoding("GB2312");
            }
            else
            {
                outputFileName = HttpUtility.UrlEncode(fileName);
                filePath += "/" + fileName;
                encoding = Encoding.Default;
            }
            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            byte[] bytes = new byte[(int)fs.Length];
            fs.Read(bytes, 0, bytes.Length);
            fs.Close();
            Response.Charset = "UTF-8";
            Response.ContentType = "application/octet-stream";
            Response.ContentEncoding = encoding;
            Response.AddHeader("Content-Disposition", "attachment; filename=" + outputFileName);
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();
            return new EmptyResult();
        }

        #endregion 
    }
}